import {
    getApiOrganizationTree as GetOrgs,
    postApiOrganization as Create,
    putApiOrganizationById as Update,
} from '@/services/furion-cms/organization';
import ProForm, {
    ModalForm,
    ProFormText
} from '@ant-design/pro-form';
import React, { useRef, useEffect, useState } from 'react';
import type { ModalProps } from 'antd';
import type { ProFormInstance } from '@ant-design/pro-form';
import { message, TreeSelect } from 'antd';
import { useIntl } from 'umi';
import { DownOutlined, FolderOutlined } from '@ant-design/icons';
import type { DataNode } from 'rc-tree-select/lib/interface';

interface DetailProps {
    modalVisible?: boolean;
    recored?: API.OrgDetailDto;
    onUpdate?: (data: API.OrgDto[]) => void;
    onVisibleChange: (visit: boolean) => void;
    modalProps?: Omit<ModalProps, 'visible'>;
}

export const DetailViewer: React.FC<DetailProps> = (props) => {
    const { modalVisible, onUpdate, onVisibleChange, modalProps, recored } = props;
    /**
       * @en-US International configuration
       * @zh-CN 国际化配置
       * */
    const intl = useIntl();

    // 绑定一个 ProFormInstance 实例
    const formRef = useRef<ProFormInstance<API.OrgCreateAndUpdateDto>>();
    const [treeData, setTreeData] = useState<DataNode[]>([]);

    const formattedDataHandle = (inputs: API.OrgDto[]): DataNode[] => {
        return inputs.filter(t => t.id != recored?.id).map(m => ({ icon: <FolderOutlined />, title: m.name!, value: m.id!, children: formattedDataHandle(m.children ?? []) }));
    }

    useEffect(() => {
        if (modalVisible) {
            (async () => {
                try {
                    const { data } = await GetOrgs({});
                    console.log('setTreeData', data);
                    setTreeData(formattedDataHandle(data ?? []));
                } catch { }
            })();
        }
    }, [modalVisible, recored]);

    const finishHandle = (values: API.OrgCreateAndUpdateDto) => {
        console.log('finishHandle', values);
        const successHandle = (result: API.SimpleResultListOrgDto) => {
            message.success(intl.formatMessage({
                id: 'pages.org.detail.save.success',
                defaultMessage: '组织机构保存成功'
            }));
            onUpdate?.(result.data ?? []);
            return true;
        }
        if (recored?.id) {
            return Update({ id: recored?.id }, { ...values })
                .then(successHandle);
        }
        else {
            return Create({ ...values })
                .then(successHandle);
        }
    }

    return (
        <ModalForm<API.OrgCreateAndUpdateDto>
            title={recored?.id ? intl.formatMessage({
                id: 'pages.org.detail.title.create',
                defaultMessage: '创建组织机构'
            }) : intl.formatMessage({
                id: 'pages.org.detail.title.edit',
                defaultMessage: '编辑组织机构'
            })}
            modalProps={{
                destroyOnClose: true,
                width: 400,
                maskClosable: false,
                ...modalProps
            }}
            visible={modalVisible}
            initialValues={recored}
            onFinish={finishHandle}
            formRef={formRef}
            onVisibleChange={onVisibleChange}
        >
            <ProFormText
                name="name"
                label={intl.formatMessage({
                    id: 'pages.org.detail.input.name',
                    defaultMessage: '组织机构名称'
                })}
                placeholder={intl.formatMessage({
                    id: 'pages.org.detail.input.name.placeholder',
                    defaultMessage: '请输入您要使用的组织机构名称'
                })}
                rules={[
                    {
                        required: true, message: intl.formatMessage({
                            id: 'pages.org.detail.input.name.rules',
                            defaultMessage: '组织机构名称必填'
                        })
                    },
                ]}
                required />
            <ProForm.Item
                name="parentId"
                label={intl.formatMessage({
                    id: 'pages.org.detail.input.parent',
                    defaultMessage: '上级组织机构'
                })}
                tooltip={intl.formatMessage({
                    id: 'pages.org.detail.input.parent.tip',
                    defaultMessage: '仅展示可移动到的上级组织机构树'
                })}
            >
                <TreeSelect
                    showSearch
                    switcherIcon={<DownOutlined />}
                    style={{ width: '100%' }}
                    dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                    placeholder={intl.formatMessage({
                        id: 'pages.org.detail.input.parent.placeholder',
                        defaultMessage: '默认为根组织机构'
                    })}
                    treeData={treeData}
                    allowClear
                    treeDefaultExpandAll
                />
            </ProForm.Item>
        </ModalForm>
    )
}